1
Easy2Siksha
GNDU Question Paper - 2020
Bachelor of Computer Application (BCA) 1st Semester
Introduction to Programming - C
Time Allowed 3 Hours Maximum Marks-75
Note :- Attempt Five question in all, selecting at least One question from each section .
The fifth question may be attempted from any section. All question carry equal marks .
SECTION-A
1. Write short notes on the following:
(a) Character set
(b) Constant
(c) Symbolic constant
(d) Reserve words
(e) Identifiers
2. What are different types of operators in C? What is the difference between operator
precedence and associativity? Explain.
SECTION-B
3. What are the different types of loops available in C? Explain giving suitable examples.
4. Write a program demonstrating uses of all types of storage classes available in C.
SECTION-C
5. (a) Define functions. What is the difference between formal and actual parameters?
Explain giving examples.
(b) Write recursive function for finding factorial of a given number.
2
Easy2Siksha
6. Write a program to multiply two matrices and store the result in third matrix.
SECTION-D
7. Define and distinguish between structures and unions. What are the uses of unions?
Explain giving examples.
8.Define pointer. How pointer to functions is used ? Explain giving example .
GNDU Answer Paper - 2022
Bachelor of Computer Application (BCA) 1st Semester
Introduction to Programming C
1. Write short notes on the following:
(a) Character set
Ans: Character Set in C Programming
Imagine you're creating a magical potion called a computer program. Now, every potion
needs its ingredients, and in the world of C programming, the essential ingredients are
characters. But, before we dive into the magical world of C, let's understand what a
character set is and why it matters.
What is a Character Set?
In the realm of C programming, a character set is like a magical alphabet, a collection
of symbols and characters that the computer understands. It's the foundation of
communication between the programmer and the computer. C relies on a specific
character set to interpret and execute the instructions written by the programmer.
ASCII - The Magical Alphabet of C:
In the world of C, the most commonly used character set is ASCII, which stands for
the American Standard Code for Information Interchange. Think of ASCII as the
magical alphabet that computers use to represent characters. It's a set of
3
Easy2Siksha
standardized codes, where each code corresponds to a specific character, including
letters, numbers, and special symbols.
Alphabets, Digits, and Symbols - Oh My!
The ASCII character set includes everything you might find on a traditional keyboard.
From the letters of the alphabet (both uppercase and lowercase) to digits,
punctuation marks, and various special symbols, it covers a wide range of characters.
For example, the ASCII code for the letter 'A' is 65, 'a' is 97, '1' is 49, and the
exclamation mark '!' is 33. These codes serve as a magical language that the
computer understands, allowing programmers to communicate their intentions
through a series of characters.
Escape Characters - Secret Codes:
In the enchanted world of C programming, there are special characters known as
escape characters. These characters don't represent visible symbols but instead
convey special meanings. Imagine them as secret codes that trigger specific actions
when the computer encounters them.
For instance, the escape character '\n' is like a magic spell for a new line. When you
use it in your potion (code), the cursor moves to the next line, creating a visually
appealing layout. There are escape characters for tabs, carriage returns, and more,
each adding a touch of magic to the presentation of your spells.
Extended ASCII - Adding More Spells to the Book:
While ASCII is fantastic, sometimes you need a bit more magic. That's where
Extended ASCII comes into play. It's like an expanded version of the ASCII character
set, offering additional characters and symbols.
In this extended realm, you might find characters like accented letters, additional
punctuation, and other symbols that weren't present in the original ASCII. This
extended set gives programmers a broader palette to work with, ensuring that their
magical spells can be as intricate as needed.
Unicode - Unleashing Global Magic:
As the magical potion of programming expanded to a global scale, a new and even
more powerful character set emergedUnicode. Unicode is like the grand library of
characters, covering not only the basic Latin alphabet but characters from various
writing systems around the world.
With Unicode, you can include characters from languages like Chinese, Arabic, or
Russian in your magical potions. It ensures that the language of programming is truly
universal, breaking down barriers and allowing programmers from different parts of
the world to conjure spells in their native tongues.
Constants and Variables - The Ingredients of Spells:
4
Easy2Siksha
In the realm of C programming, characters are not just standalone entities; they play
crucial roles as constants and variables. Constants are like fixed ingredients in a
potion, unchanging throughout the brewing process. Variables, on the other hand,
are like magical containers that can hold different values, allowing your spells to
adapt and evolve.
When you declare a character constant, you're essentially saying, "This particular
magical ingredient will always represent this character." Meanwhile, a character
variable is a flexible container that can hold different characters at different times,
adding a dynamic touch to your magical recipes.
Conclusion - Crafting Spells with Characters:
In the enchanted land of C programming, the character set is the magical palette that
programmers use to craft spells, or in this case, computer programs. From the basic ASCII
alphabet to the extended spells of Extended ASCII and the global incantations of Unicode,
characters are the building blocks of the magical language that computers understand.
So, as you embark on your journey into the world of C, remember that each character is a
potential ingredient for your potions, and the character set is your magical spellbook. With
the right combination of characters, escape codes, and a touch of Unicode magic, you can
conjure programs that bring your ideas to life in the digital realm
(b) Constant
Ans: Constants in C Programming:
Imagine you're building a castle, and some parts of it should never change - the stone walls,
the height of the towers, and the moat's width. Similarly, in the world of C programming, we
have constants. These are like unchanging values that stay the same throughout the
program.
What is a Constant?
In C, a constant is a value that doesn't change during the execution of a program. It's like
having a fixed piece of information that remains constant, much like the unyielding walls of
our castle.
Different Types of Constants:
1. Integer Constants:
These are whole numbers without any decimal points. For example, 5, -10, or 42. In
our castle, the number of rooms could be an integer constant.
2. Floating-point Constants:
These are numbers with decimal points. For example, 3.14 or -0.5. In our castle, the
height of a tower, measured precisely, could be a floating-point constant.
3. Character Constants:
5
Easy2Siksha
These are single characters enclosed in single quotes. For example, 'A' or '7'. In our
castle, the king's initial on a flag could be a character constant.
4. String Constants:
These are sequences of characters enclosed in double quotes. For example, "Hello,
World!". In our castle, a welcoming banner could have a string constant.
5. Declaring Constants:
In C, we use the const keyword to declare constants. It's like putting a label on
something in our castle and saying, "This shall not change!"
Example:
Here, NUMBER_OF_ROOMS is a constant with a value of 10.
Advantages of Constants:
1. Readability:
Constants make your code more readable. If you use const int MAX_HEIGHT = 100;,
it's clear that MAX_HEIGHT shouldn't change, just like the maximum height of a
tower in our castle.
2. Maintenance:
Constants make maintenance easier. If you need to change a constant, you only do it
in one place, making it less prone to errors. It's like having a blueprint for the castle;
you make changes in one master plan.
3. Understanding Code:
Constants act as markers. When you see const, you immediately know it's something
that stays the same. It's like putting a label "Unchanging" on certain aspects of your
castle.
4. Constants in Mathematical Expressions:
Imagine you're calculating the area of the castle courtyard. The length and width of
the courtyard are constants. In C, you can use constants in expressions like this:
Example:
Here, LENGTH and WIDTH are constants contributing to the calculation of the area.
6
Easy2Siksha
Constants vs. Variables:
In our castle, variables are like parts that might change - the number of guards, the amount
of supplies, etc. Constants, on the other hand, are like the unchanging foundation. Variables
can vary, but constants stay the same.
Enumerated Constants:
Sometimes, it's beneficial to have a set of related constants. Enumerated constants let you
create your own symbolic names for a list of integer constants.
Example:
Here, NORTH, SOUTH, EAST, and WEST are symbolic names representing integer constants
0, 1, 2, and 3, respectively.
Preprocessor Constants:
In C, there's a powerful tool called the preprocessor. You can use #define to create
preprocessor constants. These are like magical incantations that replace specific text in your
code before compilation.
Example:
Here, PI is a preprocessor constant that, when encountered in code, gets replaced by 3.14
during compilation.
Conclusion:
Constants in C programming provide stability and clarity to your code. They are unchanging
values that serve as anchors, making your program more readable and maintainable. Just as
the unyielding walls of a castle provide structure and permanence, constants ensure the
stability and reliability of your C programs. So, in the realm of C programming, embrace
constants as the steadfast foundations of your code's fortress.
7
Easy2Siksha
(c) Symbolic constant
Ans: Symbolic Constants in C
Let's embark on a journey into the realm of C programming and explore the concept of
symbolic constants. In simple terms, symbolic constants act like magical placeholders,
making our code more readable and flexible. Imagine them as enchanted values that bring
clarity and simplicity to the art of programming.
1. Understanding Constants:
Before we dive into symbolic constants, let's quickly grasp the concept of constants in
programming. In C, a constant is a value that remains unchanged during the execution of a
program. Constants, as the name suggests, are steadfast and do not vary.
For instance, imagine you are designing a program that calculates the area of a circle. The
value of π (pi) remains constant throughout the calculations. In traditional programming,
you might directly use the value of π (3.14159) in your code. However, this approach has a
drawback - it lacks readability.
2. The Need for Symbolic Constants:
Symbolic constants emerge as the heroes of clarity in such scenarios. Instead of scattering
the value of π throughout your code, you can create a symbolic constant named PI and
assign the value of π to it. This way, whenever you encounter PI in your code, it's like
encountering a magic symbol that represents the unchanging value of π.
3. Defining Symbolic Constants:
In C, symbolic constants are defined using the #define preprocessor directive. The syntax is
simple and elegant:
This line of code tells the compiler that whenever it encounters PI in the program, replace
it with the value 3.14159. It's like creating a magical alias for a constant value.
4. Advantages of Symbolic Constants:
Now, you might wonder, "Why bother with symbolic constants when I can directly use the
values in my code?" Well, let's uncover the magical advantages:
a. Readability:
Symbolic constants enhance the readability of your code. When someone else reads
your program or when you revisit it after some time, encountering PI instead of
3.14159 immediately communicates the purpose without requiring mental
gymnastics.
8
Easy2Siksha
b. Maintainability:
Imagine the value of π changes (hypothetically, in an alternate universe where π is
different!). Instead of searching and replacing every occurrence of 3.14159 in your
code, you only need to update the value in one place - the #define statement. This
simplifies maintenance and reduces the risk of errors.
c. Centralized Control:
Symbolic constants provide centralized control over values. By defining them at the
beginning of your program or in a dedicated header file, you create a reference point
for all the constants used in your code. This is like having a magical book of constants
that you can consult whenever needed.
d. Avoiding Magic Numbers:
Magic numbers are literal values scattered throughout code without explanation.
Symbolic constants eliminate magic numbers by replacing them with meaningful
names. For instance, instead of using 365 directly, you can create a symbolic
constant named DAYS_IN_YEAR. This transforms cryptic numbers into expressive
constants.
5. Example in Code:
Let's weave a simple spell in C code to illustrate the concept:
In this enchanted script, PI and RADIUS act as symbolic constants. If you decide to use a
different radius, you only need to update the value of RADIUS in one place. This is the magic
of symbolic constants in action.
9
Easy2Siksha
6. Best Practices:
Now that you've harnessed the power of symbolic constants, here are a few best practices
to enhance your spellcasting:
a. Uppercase Naming:
By convention, symbolic constants are named in uppercase letters to distinguish
them from variables. This convention adds a touch of magic consistency to your
code.
b. Descriptive Names:
Choose names that clearly convey the purpose of the constant. Instead of MAX, use
MAXIMUM_SCORE. This ensures that the magic symbols in your code tell a clear and
expressive story.
c. Grouping Constants:
Consider grouping related constants together, either in the main program or in a
dedicated header file. This creates a magical catalog of constants that developers
can reference.
7. Conclusion:
In the enchanting world of C programming, symbolic constants play a crucial role in
simplifying code, enhancing readability, and providing centralized control over values. They
transform mundane literals into magical symbols, making your programs more expressive
and maintainable.
So, as you embark on your programming quests, remember the power of symbolic
constants - the enchanted keys to clarity and simplicity in the mystical realm of C
programming. May your code be clear, your variables be meaningful, and your constants be
truly constant
(d) Reserve words
Ans: Reserved Words in C Programming Simplified
In the realm of programming languages, C stands tall as a versatile and powerful language.
Like any language, C has its own set of reserved words, also known as keywords. These are
words that hold a special meaning in the language, and you can't use them for other
purposes like naming variables or functions.
What are Reserved Words?
Think of reserved words as the building blocks of C programming. These words have
predefined meanings, and the compiler recognizes them for specific tasks. Trying to use
these words for something else in your program is like trying to make a car out of LEGO
bricks when the instructions clearly say it's for building a spaceship.
10
Easy2Siksha
Common Examples of Reserved Words:
int:
This word is short for "integer." It's used when you want to work with whole
numbers in your program.
float:
When you need numbers with decimal points, you use this reserved word, which
stands for floating-point.
char:
If you're dealing with individual characters, like letters or symbols, you turn to the
char reserved word.
if, else, switch:
These are part of the decision-making tools in C. They help your program make
choices based on certain conditions.
for, while, do:
Reserved words that help you control the flow of your program by creating loops.
Think of them as your program doing something repeatedly, like a dance move in a
loop.
return:
When a function is done with its task, it can use this word to send a result back.
Why Are They Reserved?
Imagine you're reading a recipe, and the instructions say, "Add one cup of flour." You
wouldn't substitute "flour" with "sugar" because the recipe won't turn out right. In the same
way, C needs to understand specific words to execute your program correctly. If you used
these words for other purposes, it would be like changing the recipe and expecting the
program to work correctly.
How to Identify Reserved Words:
Identifying reserved words is like recognizing the ingredients in a cookbook. They're the
words you see often, and they have a specific role in the recipe (your program). When you
spot words like "int," "float," "if," or "for," you know you're dealing with reserved words.
Using Reserved Words in Programs:
Let's imagine you're writing a program to calculate the average of three numbers. You might
use the reserved words like this:
11
Easy2Siksha
In this example, "int," "float," "main," "printf," "scanf," and "return" are all reserved
words. They each have a specific role in the program, and the compiler understands them to
execute the desired actions.
Evolution of Programming Languages:
Languages evolve, and so do their reserved words. Over time, new versions of C may
introduce new words to keep up with the demands of modern programming. It's like adding
new ingredients to a recipe to make it even more delicious.
Conclusion:
Reserved words in C are like the foundation of a building or the notes in a musical score.
They provide the structure and instructions that make your program function as intended.
Understanding and respecting these words is fundamental to becoming proficient in C
programming. It's akin to learning the rules of a game before you can play it well. So, the
next time you write a C program, remember that these reserved words are the key
ingredients that make your code come to life.
(e) Identifiers
Ans: Identifiers in C Programming Simplified
In the world of C programming, identifiers are like nametags for different elements in your
code. These elements can be variables, functions, arrays, or any other user-defined items.
Identifiers help the compiler understand and distinguish one element from another. Let's
12
Easy2Siksha
dive into the simplicity of identifiers in C programming, exploring what they are, how to use
them, and some dos and don'ts.
What are Identifiers?
An identifier in C is like a label that you give to various parts of your program. It's a name
that you use to identify and reference things like variables, functions, arrays, or any user-
defined element. Think of identifiers as unique nametags that you attach to different
objects in your code, making it easier for you and the compiler to keep track of them.
Rules for Naming Identifiers:
To create effective identifiers, there are a few rules you need to follow:
Valid Characters:
Identifiers can contain letters (both uppercase and lowercase), digits, and the
underscore _ character.
They must start with a letter or an underscore.
No Spaces or Special Characters:
Identifiers cannot contain spaces or special characters like @, #, $, %, etc.
They cannot be a C keyword (reserved words with special meaning in C, like int, for,
if, etc.).
Case-Sensitivity:
C is a case-sensitive language, meaning myVariable and myvariable are treated as different
identifiers.
Length Limitation:
The length of an identifier is limited, and it's good practice to keep it reasonably short and
descriptive.
Examples of Identifiers:
Let's see some examples to understand how identifiers work:
In these examples:
myAge is an identifier for an integer variable.
calculateSalary is an identifier for a floating-point variable.
printMessage is an identifier for a function.
13
Easy2Siksha
studentGrade is an identifier for a character array.
Best Practices for Naming Identifiers:
Descriptive Names:
Choose names that describe the purpose or content of the variable, function, or
array. This makes your code more readable.
Camel Case or Underscore:
Camel case (e.g., myVariableName) or underscores (e.g., my_variable_name) are
common conventions for multi-word identifiers.
Avoid Generic Names:
Names like temp, x, or value can be confusing. Use names that provide context and
meaning.
Consistency:
Be consistent in your naming conventions throughout your code. This helps maintain
a clean and understandable codebase.
Common Mistakes with Identifiers:
Reserved Keywords:
Avoid using words that are reserved for special purposes in C (e.g., int, char, while).
They have predefined meanings and can lead to errors.
Special Characters:
Don't use special characters or spaces in identifiers. Stick to letters, digits, and
underscores.
Starting with a Digit:
Identifiers must start with a letter or an underscore, not a digit.
Case Mismatch:
Remember that C is case-sensitive. Be consistent in your use of uppercase and
lowercase letters.
Why Identifiers Matter:
Identifiers are crucial for the readability and maintainability of your code. When you
give meaningful names to variables, functions, and other elements, it becomes
easier for you and other programmers to understand the purpose of each
component. Additionally, identifiers help the compiler accurately interpret and
execute your code.
Conclusion:
In the world of C programming, identifiers play a vital role in shaping the clarity and
functionality of your code. They are the names you assign to variables, functions, and other
elements, helping you and the compiler distinguish one from another. By following the rules
and best practices for naming identifiers, you contribute to the readability, maintainability,
and overall effectiveness of your C programs. So, choose your identifiers wisely, make them
descriptive, and let your code tell a clear and understandable story.
14
Easy2Siksha
2. What are different types of operators in C? What is the difference between operator
precedence and associativity? Explain.
Ans: Understanding Operators in C: Precedence and Associativity Explained
Operators in C are like the building blocks of a programming language. They perform various
operations on variables and values, enabling you to manipulate and process data in your
programs. Let's delve into the world of C operators, understanding their types, and
unraveling the concepts of operator precedence and associativity in simple words.
Types of Operators in C:
1. Arithmetic Operators:
These operators perform mathematical operations.
Examples:
2. Relational Operators:
These operators compare values and return true or false.
Examples:
3. Logical Operators:
These operators perform logical operations.
Examples:
15
Easy2Siksha
4. Assignment Operators:
These operators assign values.
Examples:
5. Increment and Decrement Operators:
These operators increase or decrease the value of a variable.
Examples:
6. Bitwise Operators:
These operators perform operations at the bit level.
Examples:
7. Conditional Operator (Ternary Operator):
This operator is a shorthand way of writing an if-else statement.
Examples:
8. size of Operator:
This operator returns the size of a variable or data type in bytes.
16
Easy2Siksha
Examples:
Operator Precedence and Associativity:
Now, let's explore the concepts of operator precedence and associativity.
Operator Precedence:
Operator precedence determines the order in which operations are performed. Some
operators have higher precedence than others, meaning they are evaluated first. For
example, in the expression a + b * c, the multiplication (*) has higher precedence than
addition (+), so b * c is evaluated first.
Example:
To override the natural precedence, parentheses can be used. Anything within parentheses
is evaluated first.
Example:
Operator Associativity:
Operator associativity comes into play when operators of the same precedence appear in an
expression. It determines the order in which operations are performed when they have the
same precedence. For example, in the expression a + b + c, the associativity of the addition
operator is left-to-right. So, the leftmost + is evaluated first.
Example:
Some operators, like assignment (=) and ternary (? :), have right-to-left associativity.
17
Easy2Siksha
Example:
Combining Precedence and Associativity:
When expressions involve multiple operators, their precedence and associativity work
together to determine the order of evaluation.
Example:
Here, 3 * 2 is evaluated first due to the higher precedence of multiplication, and then the
result is added to 5.
Use of Parentheses:
Parentheses can be used to explicitly specify the order of evaluation, overriding the natural
precedence and associativity.
Example:
Conclusion:
Understanding operators, their types, and the principles of precedence and associativity is
crucial for writing correct and efficient C programs. Precedence and associativity guide the
compiler in evaluating expressions in the intended order. Remember, when in doubt, use
parentheses to make your intentions clear
SECTION-B
3. What are the different types of loops available in C? Explain giving suitable examples.
Ans: Let's explore the different types of loops in the C programming language in simple
words.
18
Easy2Siksha
1. For Loop:
The "for" loop in C is like a friendly chef who follows a recipe step by step. It has three main
components: initialization, condition, and update.
Example:
In this example, the loop prints "Iteration 1" to "Iteration 5" because it starts with i=1,
continues as long as i is less than or equal to 5, and increments i by 1 in each iteration.
2. While Loop:
The "while" loop is like a curious explorer who repeats a task as long as a condition is true.
Example:
19
Easy2Siksha
Here, the loop prints "Count: 1", "Count: 2", and "Count: 3" because it continues as long as
count is less than or equal to 3.
3. Do-While Loop:
The "do-while" loop is like a persistent friend who insists on doing something at least once
and then repeats as long as the condition is true.
Example:
In this case, the loop prints "Attempt 1", "Attempt 2", and "Attempt 3" because it does the
task at least once and then continues as long as attempts is less than 3.
4. Nested Loops:
Nested loops are like having loops within loops, creating intricate patterns or solving
complex problems step by step.
Example:
20
Easy2Siksha
This nested loop prints coordinates like "(1, 1), (1, 2), (1, 3)", and so on. The outer loop
manages rows, and the inner loop handles columns.
5. Infinite Loop:
An infinite loop is like a task that goes on forever. It repeats without an end until an external
force stops it.
Example:
This loop will print "This is an infinite loop!" endlessly. It's important to handle infinite loops
carefully to avoid program freezing.
6. Loop Control Statements:
C provides loop control statements like "break" and "continue" to add flexibility to loops.
Example:
21
Easy2Siksha
In this example, the loop uses "continue" to skip iteration 3 and "break" to exit the loop
when i becomes 4.
Conclusion:
Loops in C are powerful tools that help you automate tasks, iterate over data, and solve
complex problems. Whether it's a "for" loop with clear steps, a "while" loop that repeats
until a condition is false, or a "do-while" loop that ensures at least one iteration, each loop
type has its unique purpose. Nested loops provide a way to create intricate patterns or solve
multi-dimensional problems, and loop control statements add flexibility to loop execution.
Understanding these loop types allows you to choose the right tool for the job and create
efficient and expressive programs.
4. Write a program demonstrating uses of all types of storage classes available in C.
Ans: Let's break down the concept of storage classes in C using a simple program. Storage classes in
C define the scope (visibility) and lifetime (duration) of variables. There are four main storage classes
in C: auto, register, static, and extern. I'll create a program that demonstrates each of these storage
classes in a straightforward manner.
#include <stdio.h>
// Function declaration
void showStatic();
// Global variable with external linkage
extern int externVar;
int main() {
// Auto Storage Class
printf("1. Auto Storage Class:\n");
auto int autoVar = 10;
printf("Inside main, autoVar = %d\n", autoVar);
// Register Storage Class
printf("\n2. Register Storage Class:\n");
register int registerVar = 20;
22
Easy2Siksha
printf("Inside main, registerVar = %d\n", registerVar);
// Static Storage Class
printf("\n3. Static Storage Class:\n");
static int staticVar = 30;
printf("Inside main, staticVar = %d\n", staticVar);
showStatic(); // Call a function to demonstrate static storage class
// External Storage Class
printf("\n4. External Storage Class:\n");
printf("Inside main, externVar = %d\n", externVar);
return 0;
}
// Auto Storage Class is the default for local variables.
void showStatic() {
static int staticVarFunction = 40;
printf("Inside showStatic, staticVarFunction = %d\n", staticVarFunction);
}
Let's go through each part of the program to understand the usage of different storage
classes:
Auto Storage Class:
The auto storage class is the default for local variables. Variables declared inside a
function without any storage class specifier are treated as auto variables.
In the program, autoVar is an auto variable inside the main function.
Register Storage Class:
The register storage class is used to hint to the compiler that the variable should be
stored in a register for faster access.
In the program, registerVar is a register variable inside the main function.
23
Easy2Siksha
Static Storage Class:
The static storage class is used for variables that need to retain their values between
function calls.
In the program, staticVar is a static variable inside the main function. Additionally,
there is a function showStatic that demonstrates the static storage class within a
function.
External Storage Class:
The extern storage class is used to declare a global variable that is defined in another
file.
In the program, externVar is an external variable declared in the main function but
defined in another file.
This program provides a hands-on demonstration of each storage class. When you
run the program, you'll see the values of variables and how they behave based on
their storage class. The output will help you understand the scope and lifetime of
variables in different contexts.
Remember, these storage classes play a crucial role in managing memory and determining
how variables behave within the program. The choice of storage class depends on the
specific requirements of your program and the characteristics you want for your variables.
SECTION-C
5. (a) Define functions. What is the difference between formal and actual parameters?
Explain giving examples.
Ans: Understanding Functions in Simple Words:
Imagine you have a magical recipe book for baking cookies. Each recipe has a set of
instructions to follow, like mixing ingredients and baking at a certain temperature. Now,
think of a function in programming as a similar set of instructions. It's a way to organize and
reuse a series of actions.
Definition of Functions:
In the world of programming, a function is a named set of instructions that performs a
specific task. It's like a mini-program within a larger program, designed to do a particular
job. Functions help break down complex tasks into smaller, manageable pieces.
Components of a Function:
Function Name: Like the title of a recipe, it's the name of the function.
Parameters: Ingredients or information that the function needs to do its job.
24
Easy2Siksha
Body: The set of instructions or actions the function performs.
Return Value: The result or output produced by the function.
Difference Between Formal and Actual Parameters:
Now, let's talk about parameters. Think of them as placeholders for ingredients in a recipe.
Formal Parameters:
Formal parameters are like empty spaces in a recipe where you list the ingredients you
need.
In programming, these are the variables listed in the function definition. They act as
placeholders for the actual values that will be provided when the function is called.
Here, a and b are formal parameters. They represent the numbers you want to add but
don't have specific values yet.
Actual Parameters:
Actual parameters are the real ingredients you put into those empty spaces when actually
using the recipe.
In programming, these are the values you provide when calling the function.
In this case, 5 and 3 are actual parameters. They fill the empty spaces (a and b) in the
function, and the result is 8.
Understanding with a Cooking Analogy:
Let's dive deeper into the cooking analogy to clarify:
Function Definition:
Imagine you have a cookie recipe with blanks for ingredients.
25
Easy2Siksha
Function Call:
When you decide to bake chocolate chip cookies, you fill in the blanks with specific
ingredients.
Here, chocolateChips and butter are the actual ingredients (actual parameters) that you put
into the recipe. The function then returns delicious chocolate chip cookies.
Practical Example in C:
Let's consider a simple C program with a function that calculates the area of a rectangle.
26
Easy2Siksha
In this program:
calculateArea is the function name.
float length and float width are formal parameters, acting as placeholders.
5.0 and 3.0 are actual parameters provided when calling the function.
The function calculates the area and returns the result.
The main function calls calculateArea with specific values and prints the result.
Benefits of Functions:
1. Modularity:
Functions help break down a large program into smaller, more manageable pieces.
It's like organizing your recipe book by category.
2. Reusability:
Once you have a great cookie recipe, you can reuse it whenever you want cookies.
Similarly, functions can be reused in different parts of a program.
3. Readability:
Functions make your code more readable. Instead of a long list of instructions, you
have well-defined tasks with clear names.
4. Maintenance:
If you want to tweak your cookie recipe, you only need to do it in one place.
Similarly, changes to a function affect all instances where it's used.
Conclusion:
Functions in programming are like recipes in cooking. They organize tasks, making code
modular, reusable, and easy to understand. Formal parameters are placeholders in the
recipe, while actual parameters are the real ingredients you provide when cooking. By
breaking down complex tasks into functions, programming becomes more manageable, just
like baking your favorite cookies using a well-organized recipe.
(b) Write recursive function for finding factorial of a given number.
Ans: Let's delve into the concept of recursive functions and explore how to write a recursive
function for finding the factorial of a given number in simple terms.
Understanding Recursion:
Recursion is a programming concept where a function calls itself to solve a smaller instance
of a problem. It's like breaking down a big problem into smaller, more manageable pieces.
Each call to the function works on a simpler version of the problem until a base case is
reached, which is a scenario where the function doesn't call itself anymore. Recursive
functions consist of two main parts: the base case and the recursive case.
27
Easy2Siksha
Factorial Function:
The factorial of a non-negative integer n, denoted as n!, is the product of all positive
integers less than or equal to n. Mathematically, it is defined as follows:
!=×(1)×(−2)×…×3×2×1n!=n×(n−1)×(n−2)×…×3×2×1
Now, let's create a recursive function in C to find the factorial of a given number.
Recursive Factorial Function in C:
#include <stdio.h>
// Function declaration
int factorial(int n);
int main() {
int num;
// Taking user input for the number
printf("Enter a non-negative integer: ");
scanf("%d", &num);
// Check if the number is non-negative
if (num < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
// Call the recursive factorial function and display the result
printf("Factorial of %d is: %d\n", num, factorial(num));
}
return 0;
}
// Recursive Factorial Function
28
Easy2Siksha
int factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;
}
// Recursive case: n! = n * (n-1)!
else {
return n * factorial(n - 1);
}
}
Understanding the Recursive Factorial Function:
Let's break down the recursive factorial function and the main program to understand each
part.
Main Program:
The program starts by taking user input for a non-negative integer.
It checks if the input is non-negative. If it's negative, it prints a message that factorial
is not defined for negative numbers.
If the input is non-negative, it calls the factorial function and displays the result.
Recursive Factorial Function (factorial function):
The factorial function takes an integer n as an argument and returns an integer.
It starts with a base case: if n is 0, the factorial is 1 (base case).
In the recursive case, it calculates the factorial using the formula:
!=×(−1)!n!=n×(n−1)!, where (n-1)! is computed by calling the factorial
function recursively.
The function keeps calling itself with a smaller value of n until the base case is
reached.
Execution Example:
Let's walk through an example to understand how the recursive factorial function works.
Suppose the user enters 5:
The factorial(5) is called.
It checks if n is 0 (base case not met), so it calculates 5 * factorial(4).
Now, it calls factorial(4) and repeats the process.
This continues until factorial(0) is reached (base case met). The result becomes 1.
Backtracking occurs, and each multiplication is executed, resulting in 5 * 4 * 3 * 2 *
1.
29
Easy2Siksha
The final result is 120, which is the factorial of 5.
Key Points about Recursion:
Base Case:
Every recursive function must have a base case that defines the simplest scenario
where the function doesn't call itself.
In the factorial example, the base case is when n is 0, and the factorial is 1.
Recursive Case:
The recursive case defines how the function calls itself with a smaller instance of the
problem.
In the factorial example, the recursive case is !=×(−1)!n!=n×(n−1)!.
Backtracking:
When the base case is reached, the function starts returning values back through the chain
of recursive calls, performing calculations on the way.
Stack Memory:
Recursive calls are managed through the system's call stack, and each call occupies a
portion of the stack.
It's essential to consider the stack depth for large inputs to avoid a stack overflow.
Conclusion:
In summary, a recursive function for finding the factorial of a given number is a powerful
and elegant way to solve a repetitive problem by breaking it down into smaller instances.
Understanding the base case and recursive case is crucial in designing effective recursive
functions. While recursion might seem magical, it's essentially a systematic way of solving
problems by dividing and conquering.
6. Write a program to multiply two matrices and store the result in third matrix.
Ans: Let's break down the process of multiplying two matrices and storing the result in a
third matrix using a simple C program. Matrices are mathematical structures that consist of
rows and columns. Matrix multiplication is a fundamental operation in linear algebra, and
implementing it in a programming language like C can be a great way to understand the
concepts involved.
30
Easy2Siksha
31
Easy2Siksha
Now, let's break down the program and understand each part:
32
Easy2Siksha
1. Function Declarations:
The program starts with declarations of two functions: multiplyMatrices and
displayMatrix. This is a good practice in C to declare functions before using them.
2. Input for Matrices:
The program then takes input for the first and second matrices, including their
dimensions and elements. The user is prompted to enter values for each element of
the matrices.
3. Checking Compatibility for Multiplication:
Before proceeding with multiplication, the program checks if the number of columns
in the first matrix is equal to the number of rows in the second matrix. If they are not
equal, matrix multiplication is not possible, and an error message is displayed.
4. Matrix Multiplication Function:
The multiplyMatrices function is defined to perform matrix multiplication. It takes
the two input matrices (firstMatrix and secondMatrix) along with their dimensions
and calculates the product, storing the result in the resultMatrix.
5. Display Matrix Function:
The displayMatrix function is defined to display the elements of a matrix. It takes a
matrix along with its dimensions and prints each element.
6. Displaying Result Matrix:
If matrix multiplication is possible, the program calls the multiplyMatrices function to
calculate the result and then displays the resultant matrix using the displayMatrix
function.
In summary, this program is a straightforward implementation of matrix multiplication
in C. It takes input for two matrices, checks if multiplication is possible, performs the
multiplication, and displays the result. Understanding this program provides insights into
the basics of matrix operations and how they can be implemented in a programming
language like C.
SECTION-D
7. Define and distinguish between structures and unions. What are the uses of unions?
Explain giving examples.
Ans: Structures and Unions Simplified: Understanding the Basics
In the world of programming, structures and unions are like containers that hold different
types of data. They help organize and manage data in a way that makes sense for the
program. Let's dive into the basics of structures and unions, understand their differences,
and explore the uses of unions through simple examples.
33
Easy2Siksha
1. Structures (struct):
Definition: A structure is a way to group together different variables under a single name.
Each variable inside a structure is called a member or a field. It's like creating a custom data
type that holds various pieces of information.
Example: Consider a program that needs to store information about a person - their name,
age, and address. A structure can help organize this data:
In this example, struct Person defines a blueprint for holding information about a person.
person1 is a variable of type struct Person, and it contains three members: name, age, and
address.
2. Unions:
Definition: Unions are similar to structures, but with a significant difference. While
structures allow each member to have its own memory space, unions share the same
memory space for all members. This means that a union can hold only one value at a time,
and the size of the union is determined by the largest member.
Example: Let's say you want to represent a shape, and it can be either a circle or a
rectangle. A union can help in this situation:
34
Easy2Siksha
In this example, union Shape can represent either a circle with a radius or a rectangle with
length and width. The union allows you to use only one of its members at a time, making it
flexible for scenarios where only one type of information is needed.
Distinguishing Structures and Unions:
Memory Allocation:
In structures, each member has its own memory space, and the size of the structure
is the sum of the sizes of its members.
In unions, all members share the same memory space, and the size of the union is
determined by the largest member.
Data Storage:
Structures are suitable when you need to store multiple types of data
simultaneously.
Unions are suitable when you want to represent a single piece of data that could be
of different types at different times.
35
Easy2Siksha
Accessing Members:
In structures, you can access each member independently.
In unions, you access only the currently active member.
Uses of Unions with Examples:
Space Optimization:
Unions can be used to optimize memory when only one of several members is
needed at any given time.
Example: Representing a system status where only one status (e.g., idle, processing,
error) is relevant at a time.
In this example, the union Status can represent either a system status or an error code,
depending on the situation.
36
Easy2Siksha
Handling Multiple Data Types:
Unions are useful when dealing with situations where the data type can vary.
Example: Representing a variable that could be an integer, float, or character at different
times.
In this example, the union Variable can represent a variable that may be an integer, float, or
character at different times.
37
Easy2Siksha
Conclusion:
In summary, structures and unions in C provide a way to organize and manage data.
Structures are suitable when you need to store multiple types of data simultaneously, while
unions are handy when you want to represent a single piece of data that could be of
different types at different times. Unions offer flexibility and space optimization, making
them valuable in various programming scenarios. Understanding when to use structures or
unions depends on the specific requirements of your program and the nature of the data
you are dealing with.
8.Define pointer. How pointer to functions is used ? Explain giving example .
Ans: Understanding Pointers in C: A Beginner's Guide
Let's embark on a journey to demystify the concept of pointers in the C programming
language. Imagine you have a magical tool that allows you to directly interact with the
memory of your computer. Well, in C, that magical tool is called a "pointer." This guide will
break down what pointers are, how they work, and introduce the enchanting world of
function pointers.
Defining Pointers:
In the realm of programming, a pointer is like a magical arrow that points to the memory
location of a variable. Instead of directly manipulating the variable itself, you can use the
pointer to access and modify the value stored in that memory address.
38
Easy2Siksha
In this enchanting tale, ptr is our magical arrow pointing to the memory location of num.
The & symbol is the spell that retrieves the memory address of num. By using *ptr, we
access the value stored at the memory location pointed to by ptr. When you run this
program, you'll see the magic unfold with the values and memory addresses.
Working with Pointers:
Now, let's explore some basic operations you can perform with pointers, making your code
more flexible and powerful.
In this magical act, we use pointers to swap the values of num1 and num2 without directly
manipulating the variables. The power of pointers lies in their ability to directly interact with
memory, offering a more efficient and concise way to handle data.
Introduction to Function Pointers:
Now, let's step into the world of function pointersa truly enchanting concept in C.
Function pointers are like magical scrolls that can hold the memory addresses of functions.
This allows you to call different functions dynamically, adding a layer of flexibility to your
code.
39
Easy2Siksha
In this enchanting scenario, greetPtr is our magical scroll holding the memory address of a
function. By pointing it to different functions, we can dynamically choose which function to
call. This flexibility becomes particularly handy in scenarios where you want to switch
between different functionalities during runtime.
40
Easy2Siksha
Practical Example: Dynamic Calculation with Function Pointers:
Let's dive deeper into the magical world of function pointers with a practical example.
Imagine you have a wizard's hat filled with various spells for calculations, and you want to
dynamically choose the right spell based on user input.
41
Easy2Siksha
In this magical adventure, the function pointer calculate dynamically points to different
calculation functions based on user input. The program then performs the chosen
calculation, providing a dynamic and modular approach to handling various operations.
Conclusion:
And there you have itthe magical world of pointers and function pointers in C. Pointers
are your magical tools for direct interaction with memory, while function pointers bring a
dynamic and flexible aspect to your code. As you continue your journey in the world of
programming, mastering these concepts will empower you to write more efficient, flexible,
and enchanting code.
Note: This Answer Paper is totally Solved by Ai (Artificial Intelligence) So if You find Any Error Or Mistake .
Give us a Feedback related Error , We will Definitely Try To solve this Problem Or Error.